import React, { useEffect, useRef, useState }  from 'react';
import styles from './index.less';
import {Card, message} from 'antd';
import useRequest from '@ahooksjs/use-request';
import moment from 'moment';

import {findHoliday} from '@/services/spice';

const offDutyCountdown: React.FC = () => {

  const timer = useRef();
  const [Hour, setHour] = useState('');
  const [Seconds, setSeconds] = useState('');
  const [Minutes, setMinutes] = useState('');
  const [Year, setYear] = useState('');
  const [Month, setMonth] = useState('');
  const [Day, setDay] = useState('');
  const [Weekday, setWeekday] = useState('')
  const [ClosingTime, setClosingTime] = useState('')
  const [workState, setWorkState] = useState('')

  const weekdayMap = {
    1: '一',
    2: '二',
    3: '三',
    4: '四',
    5: '五',
    6: '六',
    0: '日'
  }

  const getNewDate = () => {
    const time = new Date();
    const year = time.getFullYear();
    const month = time.getMonth() + 1;
    const day = time.getDate();
    const wday = time.getDay();
    const hour = time.getHours();
    const minutes = time.getMinutes();
    const s = time.getSeconds();
    const seconds = s <= 9 ? "0" + s : s;
    // const t = `${year}年${month}月${day}日 ${hour}:${minutes}:${seconds}`
    setHour(hour)
    setSeconds(seconds)
    if (minutes < 10) {
      setMinutes(`0${minutes}`)
    } else {
      setMinutes(`${minutes}`)
    }
    setYear(year)
    setMonth(month)
    setDay(day)
    setWeekday(weekdayMap[wday])


    // 获取当前时间戳
    const currentTimestamp = new Date().getTime();

    // 获取某个时间格式的时间戳
    const newstr = year + "-" + month + "-" + day +" 17:00:00";
    /* eslint-disable */
    // const newstr = otherTime(/-/g,'/');
    /* eslint-enable */
    const date = new Date(newstr);
    const otherTimestamp = date.getTime();

    // 时间差
    let difference;
    if (otherTimestamp > currentTimestamp) {
      difference = otherTimestamp - currentTimestamp;
      setWorkState('上班中')
    } else {
      difference = currentTimestamp - otherTimestamp;
      setWorkState('已下班')
    }

    // 时
    const leave1 = difference % (24 * 3600 * 1000);
    const hours = Math.floor(leave1 / (3600 * 1000));
    // 分
    const leave2 = leave1 % (3600 * 1000);
    const minute = Math.floor(leave2 / (60 * 1000));
    // 秒
    const leave3 = leave2 % (60 * 1000);
    const second = Math.round(leave3 / 1000);
    // console.log(hours + ":" + minute + ":" + second);
    setClosingTime(hours+":"+minute+":"+second);

  }

  // eslint-disable-next-line react-hooks/rules-of-hooks
  useEffect(() => {
    findHolidayRun({ current: 1, pageSize: 5})
    timer.current = setInterval(getNewDate, 1000);
    return () => {
      clearTimeout(timer.current)
    }
    // eslint-disable-next-line
  }, [])

  const [ Holiday, setHoliday ] = useState<SPICEAPI.SPICE[]>([]);

  // eslint-disable-next-line react-hooks/rules-of-hooks
  const { run: findHolidayRun, loading: searchLoading } = useRequest(
    findHoliday,
    {
      debounceInterval: 300,
      manual: true,
      onSuccess: (res) => {
        const { code, data: { records = [] } = {}, message: errorMessage } = res;
        if (code === 200) {
          setHoliday(records);
        } else {
          message.error(errorMessage);
        }
      },
    },
  );

  const timeDifference = ({year, month, day}: { year: any, month: any, day: any }) => {

    const now = new Date();
    const endDate = new Date(year, month.toString().replace(year, '') - 1, day.toString().replace(month, ''), 24);
    let leftTime = endDate.getTime() - now.getTime();//计算剩余的毫秒数
    if (leftTime <= 0) {
      leftTime = 0;
    }
    const leftsecond = parseInt(String(leftTime / 1000));//计算剩余的秒数
    const countDay = Math.floor(leftsecond / (60 * 60 * 24));
    return  countDay;
  }

  const items = Holiday.map((t) => (
    <div key={t.id}>
      <span>距离</span>
      <span>{ t.holidayCn !== '非节假日' ? t.holidayCn : t.weekendCn }</span>
      <span>还有:</span>
      <span>{ timeDifference({year: t.year, month: t.month, day: t.date}) }</span>
      <span>天</span>
    </div>
  ))

  // 判断是否下班
  // const workState = () => (
  //
  // ))

  return (
    <div className="site-card-wrapper">
      <Card bordered={false} className={styles.important}>
        <div>
          <div className={styles.current_time}>
            {Month && <span style={{ fontWeight: 'bold' }}>
              {`${Year}年${Month}月${Day}日`}
            </span>}
            <span className='hourclass' style={{ marginLeft: 10, fontWeight: 'bold' }}>
              <span>{Hour}</span>
              {Hour && <span style={{ margin: '0 2px' }}>{':'}</span>}
              <span>{Minutes}</span>
              {Minutes && <span style={{ margin: '0 2px' }}>{':'}</span>}
              {Seconds}
            </span>
            {Weekday && <span style={{ marginLeft: 50, fontWeight: 'bold' }}>
              {`星期${Weekday}`}
            </span>}
          </div>

          <div className={styles.hint1}>
            <div>你好，摸鱼人，工作再累，一定不要忘记摸鱼哦！</div>
            <div>有事没事起身去茶水间去廊道去天台走走，别老在工位上坐着。</div>
            <div>多喝点水，钱是老板的，但命是自己的！</div>
          </div>

          <div className={styles.holiday}>

            {items}

          </div>

          <div className={styles.closing_time}>
            <span>
              {workState === '上班中' ? (<span>此时距离下班还有</span>) : null}
              {workState === '已下班' ? (<span>已加班</span>) : null}
              <span>{ClosingTime}</span>
            </span>
          </div>

          <div className={styles.hint2}>
            {workState === '上班中' ? (<div>{'请提前整理好自己的桌面' + `\u00A0\u00A0\u00A0\u00A0` + '到点下班'}</div>) : null}
            {workState === '已下班' ? (<div>{'今天的事儿能拖就拖' + `\u00A0\u00A0\u00A0\u00A0` + '明天的事儿明天再说'}</div>) : null}
          </div>

          <div className={styles.hint3}>
            <div>[友情提示] 三甲医院  ICU躺一天平均费用一万块。</div>
            <div>你晚一天进ICU就等于为你的家庭多赚一万块。</div>
            <div>少上班，多摸鱼</div>
          </div>

        </div>
      </Card>
    </div>
  );



};

export default offDutyCountdown;
